#include <iostream>
#include <string>

#include <strings.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <pthread.h>

void usage(char* argv[])
{
    std::cout << "Usage:\n\t";
    std::cout << argv[0] << " server_ip server_port" << std::endl;
}

struct SockInfo
{
    SockInfo(int sockfd, const struct sockaddr_in& sockaddr)
        : _sockfd(sockfd)
        , _sockaddr(sockaddr)
    {}

    int _sockfd;
    struct sockaddr_in _sockaddr;
};

void* recvMessage(void* args)
{
    SockInfo* sockInfo = (SockInfo*)args;
    while(true)
    {
        char buffer[1024];
        int n = recvfrom(sockInfo->_sockfd, buffer, sizeof(buffer) - 1, 0, nullptr, nullptr);
        if (n > 0)
        {
            buffer[n] = '\0';
            std::cout << buffer << std::endl;
        }
    }

    return nullptr;
}

void* sendMessage(void* args)
{
    SockInfo* sockInfo = (SockInfo*)args;
    std::string message;
    while(true)
    {
        std::getline(std::cin, message);
        
        sendto(sockInfo->_sockfd, message.c_str(), message.size(), 
        0, (sockaddr*)&sockInfo->_sockaddr, sizeof(sockInfo->_sockaddr));
    }

    return nullptr;
}

int main(int argc, char* argv[], char* env[])
{
    if (argc != 3)
    {
        usage(argv);
        return 0;
    }

    std::string ip = argv[1];
    uint16_t port = std::stoi(argv[2]);

    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);

    struct sockaddr_in server;
    bzero(&server, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = inet_addr(ip.c_str());
    server.sin_port = htons(port);

    SockInfo sockInfo(sockfd, server);
    pthread_t sender;
    pthread_t recver;
    pthread_create(&sender, 0, sendMessage, &sockInfo);
    pthread_create(&recver, 0, recvMessage, &sockInfo);

    pthread_join(sender, nullptr);
    pthread_join(recver, nullptr);

    return 0;
}